package com.kotlin.coroutine.to_use.domain

import com.kotlin.coroutine.config.logger
import com.kotlin.coroutine.mybatis.ContentMapper
import com.kotlin.coroutine.mybatis.GameMapper
import kotlinx.coroutines.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.*
import kotlin.collections.ArrayList

/***
 * 使用suspend链式调用
 */
@Service
class SearchService {

    @Autowired
    private lateinit var gameMapper: GameMapper

    @Autowired
    private lateinit var contentMapper: ContentMapper

    // 协程
    suspend fun matchQuery(word: String): SearchResponseDTO {
        val beginTime: Long = Date().time
        logger.info("1查询开始：")
        val gameList = query1(word)
        val contentList = query2(word)
        logger.info("1查询完成，共用时" + (Date().time - beginTime) + "毫秒")

        return SearchResponseDTO(gameList, contentList)
    }
    // 同步
    fun matchQuery2(word: String): SearchResponseDTO {
        val beginTime: Long = Date().time
        logger.info("2查询开始：")

//        val gameList = gameMapper.matchQuery(word)
//        val contentList = contentMapper.matchQuery(word)

        return runBlocking {
            val gameList = query1("")
            val contentList = query2("")
            SearchResponseDTO(gameList, contentList)
        }

        logger.info("2查询完成，共用时" + (Date().time - beginTime) + "毫秒")

//        return SearchResponseDTO(gameList, contentList)
    }

    // 待协程测试
    suspend fun query1(word: String): ArrayList<SearchGameDTO> {
        return withContext(Dispatchers.IO) {  // 👈 切换到 IO 线程，并在执行完成后切回 UI 线程
            gameMapper.matchQuery(word)       // 👈 将会运行在 IO 线程
        }
    }

    suspend fun query2(word: String): ArrayList<SearchContentDTO> {
        return withContext(Dispatchers.IO) {  // 👈 切换到 IO 线程，并在执行完成后切回 UI 线程
            contentMapper.matchQuery(word)       // 👈 将会运行在 IO 线程
        }
    }



    companion object {
        private val logger = logger<SearchService>()
    }
}